<template>
  <div class="page-container">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item>材料写作</el-breadcrumb-item>
        <el-breadcrumb-item>总结材料</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="header-title">
        <h1>
          <el-icon class="title-icon"><DocumentChecked /></el-icon>
          总结材料生成
        </h1>
        <p class="subtitle">专业的总结材料生成工具，规范流程，高质量输出</p>
      </div>
      
      <!-- 进度指示器 -->
      <div class="steps-container">
        <el-steps :active="currentStep" align-center>
          <el-step title="要素信息" icon="EditPen" />
          <el-step title="基础信息" icon="InfoFilled" />
          <el-step title="生成全文" icon="DocumentChecked" />
        </el-steps>
      </div>
    </div>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 步骤1: 要素信息 -->
      <div v-show="currentStep === 0" class="step-panel">
        <el-card class="step-card">
          <template #header>
            <div class="card-header">
              <el-icon><EditPen /></el-icon>
              <span>要素信息</span>
            </div>
          </template>
          
          <el-form :model="essentialForm" label-width="100px" class="step-form">
            <el-row :gutter="40">
              <el-col :span="24">
                <el-form-item label="总结类型" required>
                  <el-radio-group v-model="essentialForm.summaryType">
                    <el-radio value="work-summary">
                      工作总结
                      <div class="radio-description">年度/季度/项目</div>
                    </el-radio>
                    <el-radio value="study-summary">
                      学习总结
                      <div class="radio-description">培训/主题教育</div>
                    </el-radio>
                    <el-radio value="activity-summary">
                      活动总结
                      <div class="radio-description">会议/赛事/宣传活动</div>
                    </el-radio>
                    <el-radio value="other">
                      其他
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="主题" required>
                  <el-input
                    v-model="essentialForm.theme"
                    placeholder="请输入主题"
                    maxlength="200"
                    show-word-limit
                  />
                  <div class="word-count">0 / 200</div>
                </el-form-item>
                
                <el-form-item label="内容">
                  <el-input
                    v-model="essentialForm.content"
                    type="textarea"
                    :rows="8"
                    placeholder="请输入内容"
                    maxlength="3000"
                    show-word-limit
                  />
                  <div class="word-count">0 / 3000</div>
                </el-form-item>
                
                <el-form-item label="篇幅" required>
                  <el-radio-group v-model="essentialForm.length">
                    <el-radio value="1500">1500字左右</el-radio>
                    <el-radio value="2000">2000字左右</el-radio>
                    <el-radio value="2500">2500字左右</el-radio>
                    <el-radio value="custom">自定义</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>

      <!-- 步骤2: 基础信息 -->
      <div v-show="currentStep === 1" class="step-panel">
        <el-card class="step-card">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>基础信息</span>
            </div>
          </template>
          
          <el-form :model="basicForm" label-width="120px" class="step-form">
            <el-row :gutter="40">
              <el-col :span="24">
                <el-form-item label="应用场景">
                  <el-radio-group v-model="basicForm.applicationScenario">
                    <el-radio value="report-up">向上级报送</el-radio>
                    <el-radio value="internal-archive">内部存档</el-radio>
                    <el-radio value="meeting-report">会议汇报</el-radio>
                    <el-radio value="external-publicity">对外宣传</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="主体性质">
                  <el-radio-group v-model="basicForm.subjectNature">
                    <el-radio value="unit-summary">
                      单位总结
                      <div class="radio-description">部门/机构</div>
                    </el-radio>
                    <el-radio value="personal-summary">个人总结</el-radio>
                    <el-radio value="joint-summary">
                      联合总结
                      <div class="radio-description">多部门协作项目</div>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="其他写作信息">
                  <el-input
                    v-model="basicForm.otherInfo"
                    type="textarea"
                    :rows="8"
                    placeholder="请输入其他写作信息"
                    maxlength="3000"
                    show-word-limit
                  />
                  <div class="word-count">0 / 3000</div>
                </el-form-item>
                
                <el-form-item label="参考文档">
                  <el-upload
                    class="upload-demo"
                    drag
                    action="#"
                    :auto-upload="false"
                    :file-list="uploadFiles"
                    accept=".doc,.docx,.xls,.xlsx,.pdf,.txt"
                  >
                    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">
                      拖拽文件到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持word、excel，文件2mb以内，最多一万字
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>

      <!-- 步骤3: 生成结果 -->
      <div v-show="currentStep === 2" class="step-panel">
        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <el-icon><DocumentChecked /></el-icon>
              <span>生成结果</span>
              <div class="header-actions" v-if="generatedContent">
                <el-button type="success" text @click="copyResult" :icon="DocumentCopy">
                  复制结果
                </el-button>
                <el-button type="primary" text @click="exportDocument" :icon="Download">
                  导出文档
                </el-button>
              </div>
            </div>
          </template>
          
          <div v-if="!generatedContent && !generating" class="empty-result">
            <el-empty description="请完善前面步骤的信息，然后点击生成材料">
              <template #image>
                <el-icon size="80" color="#ddd"><Document /></el-icon>
              </template>
            </el-empty>
          </div>
          
          <div v-else-if="generating" class="generating-indicator">
            <el-skeleton :rows="12" animated />
            <div class="generating-text">
              <el-icon class="is-loading"><Loading /></el-icon>
              AI正在根据您的要求生成专业的总结材料，请稍候...
            </div>
          </div>
          
          <div v-else class="content-preview">
            <el-scrollbar height="600px">
              <div class="generated-content" v-html="formattedContent"></div>
            </el-scrollbar>
            
            <el-divider />
            
            <div class="content-stats">
              <el-statistic title="生成字数" :value="generatedContent?.length || 0" />
              <el-statistic title="段落数" :value="paragraphCount" />
              <el-statistic title="预计阅读" :value="readingTime" suffix="分钟" />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="step-actions">
      <el-button 
        v-if="currentStep > 0" 
        @click="prevStep"
        size="large"
      >
        上一步
      </el-button>
      
      <el-button 
        v-if="currentStep < 2"
        type="danger" 
        @click="nextStep"
        size="large"
        :disabled="!canProceed"
      >
        下一步
      </el-button>
      
      <el-button 
        v-if="currentStep === 2"
        type="danger" 
        @click="generateContent"
        :loading="generating"
        size="large"
      >
        <el-icon><Magic /></el-icon>
        {{ generating ? '生成中...' : '生成材料' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy, Download } from '@element-plus/icons-vue'
import { useModelConfigStore } from '@/stores/modelConfig'

const modelStore = useModelConfigStore()

// 当前步骤
const currentStep = ref(0)
const generating = ref(false)
const generatedContent = ref('')
const uploadFiles = ref([])

// 要素信息表单
const essentialForm = reactive({
  summaryType: '',
  theme: '',
  content: '',
  length: '1500'
})

// 基础信息表单
const basicForm = reactive({
  applicationScenario: '',
  subjectNature: '',
  otherInfo: '',
  referenceFiles: []
})

const formattedContent = computed(() => {
  return generatedContent.value.replace(/\n/g, '<br/>').replace(/\s{2,}/g, '&nbsp;&nbsp;')
})

const paragraphCount = computed(() => {
  return generatedContent.value.split('\n\n').filter(p => p.trim()).length
})

const readingTime = computed(() => {
  const wordsPerMinute = 200
  const wordCount = generatedContent.value.length
  return Math.ceil(wordCount / wordsPerMinute)
})

// 计算属性
const canProceed = computed(() => {
  if (currentStep.value === 0) {
    return essentialForm.summaryType && essentialForm.theme.trim() && essentialForm.length
  }
  return true
})

// 步骤控制方法
const nextStep = () => {
  if (!canProceed.value) return
  
  if (currentStep.value < 2) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 生成内容
const generateContent = async () => {
  if (!essentialForm.summaryType || !essentialForm.theme.trim()) {
    ElMessage.warning('请完善要素信息')
    return
  }

  // 检查模型配置
  const currentProvider = modelStore.getCurrentProvider()
  const currentModel = modelStore.getCurrentModel()
  
  if (!currentProvider?.hasApiKey) {
    ElMessage.warning('请先在模型配置中设置API密钥')
    return
  }
  
  generating.value = true
  
  try {
    ElMessage.info(`使用${currentModel?.name}模型生成总结材料...`)
    
    // 调用真实的AI服务
    const { aiService } = await import('@/services/aiService')
    
    // 构建系统提示词
    const systemPrompt = `你是一位专业的公务员文件写作助手，擅长撰写各类总结材料。请根据用户提供的信息，生成一份规范、清晰、具有政治高度的${essentialForm.length}字左右的总结材料。`
    
    // 构建用户提示词
    let userPrompt = `请帮我生成一份总结材料：

总结类型：${essentialForm.summaryType}
主题：${essentialForm.theme}
篇幅要求：${essentialForm.length}字左右

主要内容：
${essentialForm.content}

应用场景：${basicForm.applicationScenario}
主体性质：${basicForm.subjectNature}

${basicForm.otherInfo ? '其他写作信息：\n' + basicForm.otherInfo : ''}

请生成一份结构清晰、语言规范、政治站位高的总结材料。`

    const response = await aiService.generateText({
      systemPrompt,
      userPrompt,
      config: {
        temperature: modelStore.globalConfig.temperature,
        maxTokens: modelStore.globalConfig.maxTokens
      }
    })
    
    generatedContent.value = response.content
    
    ElMessage.success(`总结材料生成完成！用时${response.duration}ms，消耗${response.usage.total_tokens}个tokens${response.cost ? `，成本$${response.cost.toFixed(6)}` : ''}`)
  } catch (error) {
    ElMessage.error('生成过程中出现错误，请重试')
    console.error('Generation error:', error)
  } finally {
    generating.value = false
  }
}

const copyResult = () => {
  if (!generatedContent.value) return
  
  navigator.clipboard.writeText(generatedContent.value).then(() => {
    ElMessage.success('内容已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

const exportDocument = () => {
  const blob = new Blob([generatedContent.value], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${essentialForm.theme || '总结材料'}_${new Date().toISOString().split('T')[0]}.txt`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('文档导出成功')
}

// 初始化
onMounted(() => {
  modelStore.initConfig()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 30px;
}

.header-title {
  margin-top: 16px;
  text-align: center;
}

.header-title h1 {
  color: #dc3545;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 28px;
  font-weight: 600;
}

.title-icon {
  font-size: 32px;
}

.subtitle {
  color: #666;
  margin: 12px 0 0 0;
  font-size: 16px;
}

.steps-container {
  margin-top: 30px;
  padding: 0 20px;
}

.step-content {
  margin: 30px 0;
  min-height: 500px;
}

.step-panel {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.step-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 16px;
}

.card-header > span {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.step-form {
  padding: 20px 10px;
}

.radio-description {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.word-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.upload-demo {
  margin-top: 12px;
}

.result-card {
  min-height: 600px;
}

.empty-result {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.generating-indicator {
  padding: 30px;
}

.generating-text {
  text-align: center;
  margin-top: 30px;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 16px;
}

.content-preview {
  max-height: 700px;
}

.generated-content {
  white-space: pre-wrap;
  line-height: 2;
  font-size: 14px;
  color: #333;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.content-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.content-stats .el-statistic {
  text-align: center;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background: white;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.step-actions .el-button {
  min-width: 120px;
  padding: 12px 30px;
  font-size: 16px;
}

/* Element Plus Steps 自定义样式 */
:deep(.el-steps) {
  margin: 0 auto;
  max-width: 600px;
}

:deep(.el-step__title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-step__title.is-process) {
  color: #dc3545;
  font-weight: 600;
}

:deep(.el-step__icon.is-process) {
  color: #dc3545;
  border-color: #dc3545;
}

:deep(.el-step__line) {
  background-color: #e4e7ed;
}

:deep(.el-step__line.is-process) {
  background-color: #dc3545;
}

/* Element Plus Radio 自定义样式 */
:deep(.el-radio) {
  margin: 0 20px 16px 0;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

:deep(.el-radio:hover) {
  border-color: #dc3545;
  background-color: #fdf2f2;
}

:deep(.el-radio.is-checked) {
  border-color: #dc3545;
  background-color: #fdf2f2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 15px;
  }
  
  .header-title h1 {
    font-size: 24px;
    flex-direction: column;
    gap: 8px;
  }
  
  .step-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .step-actions .el-button {
    width: 100%;
    max-width: 300px;
  }
}
</style>